/**
 * 
 */
package com.gopay.webtest.controller;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.webtest.controller.base.BaseController;
import com.gopay.webtest.util.BaseSign;
import com.gopay.webtest.xml.XmlDao;

/**
 * @BtController.java
 * @author gz
 * @2013-7-26 上午11:01:46 www.gopay.com.cn Inc.All rights reserved.
 */
@Controller
@RequestMapping("/bt")
public class BtController extends BaseController {

	private static Logger logger = Logger.getLogger(BackgroundMerController.class);
	
	private static String CHARSET_GBK = "1";
	
	@Autowired
	private XmlDao xmlDao;
	
	@Resource(name = "Sign4BtHandler")
	private BaseSign Sign4BtHandler;

	/**
	 * 设置签约报文的参数
	 * 
	 * @param res
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/index")
	public ModelAndView directUrl(HttpServletResponse res,
			HttpServletRequest req, String type) {
		String mvPrefix = "gopay.webtest.bt.";
		ModelAndView mv = new ModelAndView(mvPrefix + type);
		Map<String, String> info = new HashMap<String, String>();
        try {
        	info = xmlDao.readData4Map("blocktrade", type + "Apply");
            info.put("tranDateTime", com.gopay.webtest.util.DateUtils.date2string(new Date(),com.gopay.webtest.util.DateUtils.DEFAULT_PATTERN ));
            info.put("tranIP", getRemoteRealIpAddr(req));
            info.put("verficationCode", getVerifyCode());
            
        } catch (DocumentException e) {                     
            logger.warn(e.getMessage(), e);
        } catch (IOException e) {                    
            logger.warn(e.getMessage(), e);
        }
        mv.addObject("info", info);
		return mv;
	}

	/**
	 * 提交签约报文的参数到网关
	 * 
	 * @param res
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/redirect/submit")
	public ModelAndView redirectUrl(HttpServletResponse res,
			HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("");
		Map<String, String> parameters = this.listParameters(req);
		
		//MD5加密
        try {
            Sign4BtHandler.sign(
            		parameters.get("tranCode")+"_"+parameters.get("version"),
                    "signType", "signValue", parameters, req);
            System.out.println("后台notify密文值:" + parameters.get("signValue"));
        } catch (Exception e) {
            logger.warn(e.getMessage());
            e.printStackTrace();         
        }
        if (!CHARSET_GBK.equalsIgnoreCase(parameters.get("charset"))) {
			mv.setViewName("gopay.webtest.bt.redirect");
		} else {
			mv.setViewName("gopay.webtest.bt.redirect.gbk");
		}
		mv.addObject("info", parameters);
		return mv;
	}

	/**
     * 将Request中的数据转换成Map
     */
    @SuppressWarnings("rawtypes")
    Map<String, String> listParameters(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        for (Enumeration enumeration = request.getParameterNames(); enumeration.hasMoreElements();) {
            String eleName = (String) enumeration.nextElement();
            String eleValue = request.getParameter(eleName);
            logger.error("网关收到的请求参数键: [" + eleName + "]，值: [" + eleValue + "]");
            params.put(eleName, eleValue);
        }
        return params;
    }
}
